<template>
  <view>
    <!-- <u-navbar
      :is-back="false"
      :background="navbarBackground"
      :height="navigationHeight"
    >
    </u-navbar> -->
    <view class="supplier-wrap">
      <view class="supplier-list" v-for="(item, index) in dataList" :key="index">
        <view class="supplier-list-hd am-flex-row-center">
          <view class="supplier-list-hd-checkbox">
            <u-checkbox v-model="item.my_self_check_all" shape="circle" :size="40" active-color="#4BB019"
              @change="allCheckboxChange" :name="index" :disabled="item.my_self_all_disabled"></u-checkbox>
          </view>
          <text class="supplier-list-name am-text-eill">{{
            item.supplierVO.name
          }}</text>
        </view>
        <view class="supplier-goods-wrap">
          <view class="cart-goods-item am-flex-row-center" v-for="(list, indNum) in item.cartProductVOList"
            :key="list.cartId">
            <view class="cart-goods-checkbox-wrap">
              <u-checkbox v-model="list.my_self_checked" shape="circle" :size="40" :name="index" :disabled="list.proxyBuyProductVO.stock === 0 ||
                list.proxyBuyProductVO.buyProductStatus == 1 ||
                list.proxyBuyProductVO.buyProductStatus == 2
                " active-color="#4BB019" @change="goodsCheckboxChange"></u-checkbox>
            </view>
            <view class="goods-box" @click="
              goToDetails(
                list.proxyBuyProductVO.id,
                list.proxyBuyProductVO.buyProductStatus
              )
              ">
              <view class="goods-box-cover">
                <image :src="list.my_self_cover" mode="aspectFill" webp class="goods-box-cover-img am-block"></image>
                <view class="goods-box-sell-out am-flex-rc-center" v-if="
                  list.proxyBuyProductVO.stock === 0 &&
                  list.proxyBuyProductVO.buyProductStatus == 0
                ">
                  <image src="/static/images/icon-sell-out.png" mode="aspectFill" class="goods-sell-out-img am-block">
                  </image>
                </view>
                <view class="goods-box-sell-out am-flex-rc-center" v-if="list.proxyBuyProductVO.buyProductStatus == 1">
                  <image src="/static/images/icon-sell-bottom.png" mode="aspectFill"
                    class="goods-sell-out-imgs am-block"></image>
                </view>
                <view class="goods-box-sell-out am-flex-rc-center" v-if="list.proxyBuyProductVO.buyProductStatus == 2">
                  <image src="/static/images/icon-sell-delete.png" mode="aspectFill"
                    class="goods-sell-out-imgs am-block"></image>
                </view>
              </view>
              <view class="goods-box-con">
                <view>
                  <view class="goods-title-section">
                    <text class="goods-box-name am-line-clamp-two am-text-break">{{ list.proxyBuyProductVO.name
                      }}</text>
                    <view class="goods-box-del" :data-cart-id="list.cartId"
                      @click.stop="delGoods($event, index, indNum)">
                      <image src="@/static/images/icon-trash.png" mode="aspectFill" class="goods-box-del-img am-block">
                      </image>
                    </view>
                  </view>
                </view>
                <view><text class="specStyle">{{
                  list.proxyBuyProductVO.spec
                    }}</text></view>
                <view>
                  <text class="original-price">
                    <text style="font-size: 24rpx">￥</text>
                    {{ list.proxyBuyProductVO.finalProxyPrice }}
                    <text style="font-size: 24rpx">元</text>
                  </text>
                </view>
                <view class="goods-box-con-ft am-flex-rc-between">
                  <div v-if="!isShow" class="membership-price">会员价</div>
                  <text class="am-block goods-box-price am-text-eill">
                    <text style="font-size: 24rpx">￥</text>
                    {{ list.proxyBuyProductVO.finalProxyPrice }}
                    <text style="font-size: 24rpx">元</text>
                  </text>
                  <view class="pedometer-wrap" @click.stop="() => { }">
                    <u-number-box v-model="list.num" @blur="cartNumBlur($event, index, indNum)" @minus="
                      cartNumClickHandle($event, 'minus', index, indNum)
                      " @plus="cartNumClickHandle($event, 'plus', index, indNum)" :long-press="false" :min="1"
                      :max="99999" :input-height="54" :input-width="86" :disabled="list.proxyBuyProductVO.stock === 0"
                      :index="list.cartId" :key="list.cartId"></u-number-box>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <co-empty paddingTop="300rpx" :show="!getLoading && dataList.length === 0"></co-empty>
    <!-- 补偿footer -->
    <view class="footer-controls-place"></view>
    <view class="footer-controls am-flex-rc-between">
      <view class=""><u-checkbox :size="40" v-model="checkAll" shape="circle" active-color="#4BB019"
          @change="pageCheckAllChange">全选</u-checkbox></view>
      <view class="am-flex-row-center total-content">
        <view class="total-box">
          合计：
          <text style="color: #f65300">￥</text>
          <text class="total-box-price-num">{{
            checkedComputed.totalPrice
          }}</text>
        </view>
        <button class="u-reset-button go-pay-btn co-primary-button" @click="goPayOrder"
          hover-class="co-primary-button--hover">
          去付款{{
            checkedComputed.checkedGoodsNum === 0
              ? ''
              : `(${checkedComputed.checkedGoodsNum})`
          }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { apiCartList, apiCartNumChange, apiDelCart } from '@/api/shoppingCart'
import tabbarPage from '@/mixins/tabbarPage'
import { UPDATE_SHOPPING_CART } from '@/types/globalEventName'
import { NAV_BAR_TITLE } from '@/types/navbar.js'
import { appOnLaunch } from '@/utils/appGlobalLifeCycle'
import { navigationHeight } from '@/utils/systemInfo.js'
import Big from 'big.js'

/**
 * 采用懒加载更新方案，只有当购物车有变化，并且进入当前页面才会更新数据
 * */
export default {
  data() {
    return {
      checkAll: false, // 是否全选
      NAV_BAR_TITLE,
      dataList: [],
      navbarBackground: {
        background: 'linear-gradient(360deg, #F79128 0%, #FE6507 100%)'
      },
      navigationHeight,
      shouldUpdate: true,
      getLoading: false, // 是否正在刷新购物车
      goPayLoading: false, // 是否正在请求去付款判断
      totalGoodsNum: 0
    }
  },
  mixins: [tabbarPage],
  computed: {
    // 选中状态监听
    checkedComputed() {
      let init = new Big(0)
      let checkedGoodsNum = 0
      this.dataList.forEach((p1) => {
        p1.cartProductVOList.forEach((z1) => {
          if (z1.proxyBuyProductVO.stock !== 0 && z1.my_self_checked) {
            checkedGoodsNum += 1
            init = init.plus(
              new Big(z1.num).times(z1.proxyBuyProductVO.finalProxyPrice)
            )
          }
        })
      })
      return {
        totalPrice: Number(init),
        checkedGoodsNum
      }
    },
    isCheckAll() {
      return this.dataList.every((p1) => {
        if (p1.my_self_all_disabled) {
          return true
        } else {
          return p1.my_self_check_all
        }
      })
    }
    // checkGoodsNum() {}
  },
  watch: {
    isCheckAll(n) {
      console.log(n)
      this.checkAll = n
    }
  },
  onLoad() {
    if (!this.$store.getters.isLogin) {
      appOnLaunch()
      return
    }
    uni.$on(UPDATE_SHOPPING_CART, this.updateCartCb)
  },
  onShow() {
    if (this.shouldUpdate && !this.getLoading) {
      this.getList()
    }
  },
  onUnload() {
    uni.$off(UPDATE_SHOPPING_CART, this.updateCartCb)
  },
  onPullDownRefresh() {
    if (!this.getLoading) {
      this.getList()
    }
  },
  methods: {
    getList() {
      if (this.getLoading) return
      this.getLoading = true
      uni.showLoading({
        mask: true
      })
      apiCartList()
        .then((res) => {
          let { state, data } = res.data
          if (state === 'OK') {
            let cartList = data.length ? [{ cartProductVOList: data }] : []
            let $imageCutting = this.$imageCutting
            let goodsNum = 0
            cartList.forEach((p1) => {
              console.log(p1)
              p1.my_self_check_all = false
              let allDisabled = true
              p1.cartProductVOList.forEach((z1) => {
                goodsNum += 1
                z1.my_self_checked = false
                z1.my_self_cover = $imageCutting(
                  z1.proxyBuyProductVO.banner.split(',')[0],
                  160,
                  160
                )
                if (z1.proxyBuyProductVO.stock !== 0) {
                  allDisabled = false
                }
              })
              console.log(p1.cartProductVOList)
              p1.my_self_all_disabled = allDisabled
            })
            this.totalGoodsNum = goodsNum
            this.$store.commit('SET_CART_NUM', goodsNum)
            this.dataList = cartList
            console.log('格式化后的datalist')
            console.log(this.dataList)
            this.shouldUpdate = false
          }
          this.getLoading = false
          uni.stopPullDownRefresh()
          uni.hideLoading()
        })
        .catch((err) => {
          console.log(err)
          uni.stopPullDownRefresh()
          uni.hideLoading()
          this.$am_toast.error('数据更新失败，请重新尝试')
          this.getLoading = false
        })
    },
    goodsCoverHanlde(imgStr) {
      return this.$imageCutting(imgStr.split(',')[0], 160, 160)
    },
    // cartNumChange(e) {
    // 	console.log('goods num change');
    // 	console.log(e);
    // },
    // 删除商品
    delGoods(ev, index, secIndex) {
      let cartId = ev.currentTarget.dataset.cartId
      console.log(cartId)
      uni.showModal({
        title: '删除确认',
        content: '确定从购物车移除此商品吗？',
        confirmColor: '#4BB019',
        success: (delModal) => {
          if (delModal.confirm) {
            uni.showLoading({
              mask: true
            })
            apiDelCart({ id: cartId })
              .then((res) => {
                let { state, msg } = res.data
                if (state === 'OK') {
                  this.totalGoodsNum--
                  this.$store.commit('SET_CART_NUM', this.totalGoodsNum)
                  let dataList = [...this.dataList]
                  dataList[index].cartProductVOList.splice(secIndex, 1)
                  if (dataList[index].cartProductVOList.length === 0) {
                    dataList.splice(index, 1)
                  } else {
                    let allDisabled = true
                    let checkAll = true
                    dataList[index].cartProductVOList.forEach((p1) => {
                      if (p1.proxyBuyProductVO.stock !== 0) {
                        allDisabled = false
                        if (!p1.my_self_checked) {
                          checkAll = false
                        }
                      }
                    })
                    if (allDisabled) {
                      checkAll = false
                    }
                    dataList[index].my_self_check_all = checkAll
                    dataList[index].my_self_all_disabled = allDisabled
                  }
                  console.log('del end dataList')
                  console.log(dataList)
                  this.dataList = dataList
                  uni.hideLoading()
                  this.$am_toast.success('删除成功！')
                } else {
                  uni.hideLoading()
                  this.$am_toast.warning(msg)
                }
              })
              .catch((err) => {
                console.log(err)
                uni.hideLoading()
                this.$am_toast.error('删除失败，请重新尝试！')
              })
          }
        }
      })
    },
    // 商品的复选框change
    goodsCheckboxChange(e) {
      console.log(e)
      let index = e.name
      /* *
       * 注意：此处使用$nextTick是因为判断是否全部一样时，数据更新不及时，判断不准确，所以放到$nextTick
       * */
      this.$nextTick(function () {
        let allSame = this.dataList[index].cartProductVOList.every((p1) => {
          // 将库存为0的排除
          if (p1.proxyBuyProductVO.stock !== 0) {
            return p1.my_self_checked === e.value
          } else {
            return true
          }
        })
        let curAllStatus = this.dataList[index].my_self_check_all
        if (allSame && e.value !== curAllStatus) {
          this.$set(this.dataList[index], 'my_self_check_all', e.value)
        } else if (!allSame && curAllStatus) {
          this.$set(this.dataList[index], 'my_self_check_all', false)
        }
      })
    },
    // 全选checkbox change
    allCheckboxChange(e) {
      let dataList = [...this.dataList]
      let index = e.name
      let cartProductVOList = dataList[index].cartProductVOList
      cartProductVOList.forEach((p1) => {
        if (
          p1.proxyBuyProductVO.stock !== 0 &&
          p1.proxyBuyProductVO.buyProductStatus != 1 &&
          p1.proxyBuyProductVO.buyProductStatus != 2
        ) {
          p1.my_self_checked = e.value
        }
      })
      this.$set(this.dataList[index], 'cartProductVOList', cartProductVOList)
    },
    // 计数器失去焦点
    cartNumBlur(e, index, indNum) {
      uni.showLoading({
        mask: true
      })
      console.log('cartNumBlur')
      console.log(e)
      console.log(index)
      console.log(indNum)
      this.goCartNum({ type: 2, id: e.index, num: e.value }, { index, indNum })
    },
    // 计数器加减
    cartNumClickHandle(e, type = 'minus', index, indNum) {
      uni.showLoading({
        mask: true
      })
      console.log('cartNumClickHandle')
      console.log(e)
      console.log(type)
      let typeF = {
        minus: 0,
        plus: 1
      }
      this.goCartNum({ type: typeF[type], id: e.index }, { index, indNum })
    },
    goCartNum(p_data, indMes) {
      apiCartNumChange(p_data)
        .then((res) => {
          let { state, msg, data } = res.data
          if (state !== 'OK') {
            if (data && typeof data.num !== 'undefined') {
              console.log('3423423423')
              this.setIndexCartNum(indMes.index, indMes.indNum, data.num)
            }
            uni.hideLoading()
            this.$am_toast(msg)
          } else {
            uni.hideLoading()
          }
        })
        .catch((err) => {
          uni.hideLoading()
          this.$am_toast.error('网络错误，请刷新页面！')
        })
    },
    // 设置对应下标商品数量
    setIndexCartNum(index, indNum, num) {
      let dataList = [...this.dataList]
      let cartProductVOList = dataList[index].cartProductVOList
      cartProductVOList[indNum].num = num
      this.dataList = dataList
    },
    // 页面全选change
    pageCheckAllChange(e) {
      console.log(e)
      let dataList = [...this.dataList]
      dataList.forEach((p1) => {
        if (!p1.my_self_all_disabled) {
          p1.my_self_check_all = e.value
          p1.cartProductVOList.forEach((z1) => {
            if (
              z1.proxyBuyProductVO.stock !== 0 &&
              z1.proxyBuyProductVO.buyProductStatus != 1 &&
              z1.proxyBuyProductVO.buyProductStatus != 2
            ) {
              z1.my_self_checked = e.value
            }
          })
        }
      })
      this.dataList = dataList
    },
    goPayOrder() {
      if (this.goPayLoading) {
        return;
      }
      if (this.checkedComputed.totalPrice === 0) {
        this.$am_toast('请先选择要购买的商品')
        return
      }
      this.goPayLoading = true;
      uni.showLoading({
        mask: true
      });
      let ids = []
      let cartData = []
      this.dataList.forEach((p1) => {
        p1.cartProductVOList.forEach((z1) => {
          if (z1.proxyBuyProductVO.stock !== 0 && z1.my_self_checked) {
            ids.push(z1.cartId)
            z1.proxyBuyProductVO.num = z1.num
            cartData.push(z1.proxyBuyProductVO)
          }
        })
      })
      console.log(cartData)
      console.log(this.dataList)
      this.$u.route('/pages/place-order/submit-order', {
        pType: 'cart',
        val: JSON.stringify(cartData),
        ids: ids.toString()
      })
    },
    updateCartCb() {
      this.shouldUpdate = true
    },
    // 跳转商品详情
    goToDetails(id, status) {
      if (status == 0) {
        uni.navigateTo({
          url: `/pages/goods-details/goods-details?id=${id}`
        })
      } else {
        uni.navigateTo({
          url: `/pages/order/goods-delete`
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$goods-item-height: 160rpx;
$footer-controls-height: 98rpx;
$checkbox-margin-right: 15rpx;
$section-plr: 15rpx;

.navbar-title-img {
  display: block;
  width: 174rpx;
  height: 37rpx;
}

.supplier-wrap {
  padding: 16rpx;
}

.supplier-list {
  background: #ffffff;
  border-radius: 24rpx;
  padding-bottom: 36rpx;

  &+.supplier-list {
    margin-top: 16rpx;
  }
}

.supplier-list-hd {
  height: 88rpx;
  padding-left: $section-plr;
  padding-right: $section-plr;
}

.supplier-list-hd-checkbox {
  margin-right: $checkbox-margin-right;

  /deep/ .u-checkbox__label {
    margin-left: 0;
    margin-right: 0;
  }
}

.supplier-list-name {
  font-size: 28rpx;
  font-weight: 400;
  color: #333333;
}

.supplier-goods-wrap {}

.cart-goods-item {
  padding-left: $section-plr;
  padding-right: $section-plr;

  &+.cart-goods-item {
    margin-top: 40rpx;
  }
}

.cart-goods-checkbox-wrap {
  margin-right: $checkbox-margin-right;
  flex-shrink: 0;

  // /deep/ .u-checkbox {
  // 	padding: 55rpx;
  // }
  /deep/ .u-checkbox__label {
    margin-left: 0;
    margin-right: 0;
  }
}

.goods-box {
  display: flex;
  align-items: stretch;
  flex: 1;
  width: 0;
}

.goods-box-cover {
  position: relative;
  overflow: hidden;
  width: 160rpx;
  flex-shrink: 0;
  border-radius: 15rpx;
}

.goods-box-cover-img {
  width: 160rpx;
  height: $goods-item-height;
}

.goods-box-sell-out {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(#000, 0.5);
}

.goods-sell-out-img {
  width: 69rpx;
  height: 29rpx;
}

.goods-sell-out-imgs {
  width: 90rpx;
  height: 29rpx;
}

.goods-box-con {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 0;
  flex: 1;
  margin-left: 26rpx;
}

.goods-title-section {
  display: flex;
  // height: 80rpx;
  align-items: flex-start;
}

.goods-box-name {
  flex: 1;
  width: 0;
  font-weight: 400;
  line-height: 40rpx;
}

.goods-box-del {
  height: 50rpx;
  flex-shrink: 0;
  padding: 0 10rpx;
  margin-left: 19rpx;
}

.goods-box-del-img {
  width: 28rpx;
  height: 28rpx;
}

.goods-box-con-ft {
  // display: flex;
  // flex-direction: column;
}

.goods-box-price {
  flex: 1;
  width: 0;
  font-size: 34rpx;
  // font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #f65300;
}

.pedometer-wrap {
  flex-shrink: 0;
  margin-left: 20rpx;

  /deep/ .u-icon-disabled {
    color: #ccc;
  }

  /deep/ .u-icon-minus {
    background: transparent !important;
  }

  /deep/ .u-icon-plus {
    background: transparent !important;
  }
}

.footer-controls {
  position: fixed;
  left: 0;
  z-index: 1500;
  bottom: 0;
  width: 100%;
  height: $footer-controls-height;
  padding: 0 32rpx;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
}

.footer-controls-place {
  height: $footer-controls-height;
}

.total-content {}

.total-box {
  font-size: 24rpx;
  font-weight: 400;
  color: #000000;
}

.total-box-price-num {
  color: #f65201;
  font-size: 30rpx;
  font-weight: 500;
}

.go-pay-btn {
  min-width: 200rpx;
  height: 66rpx;
  padding: 0 29rpx;
  margin-left: 20rpx;
  line-height: 66rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: 500;
  border-radius: 32rpx;
}

.navbar-slot-wrap {
  position: absolute;
  width: 750rpx;
  left: 0;
}

.specStyle {
  margin-right: 15rpx;
  padding: 5rpx 10rpx;
  margin-bottom: 10rpx;
  background: rgba(239, 239, 244, 0.5);
  color: #999999;
  border-radius: 4rpx;
  font-size: 22rpx;
}

.membership-price {
  width: 76rpx;
  height: 32rpx;
  word-wrap: normal;
  background: #be9972;
  border-radius: 4rpx 4rpx 4rpx 4rpx;
  font-weight: 400;
  font-size: 20rpx;
  color: #ffffff;
  text-align: center;
  line-height: 32rpx;
}
</style>
